import java.io.*;
import java.net.*;
import java.util.*;

public class HTTPOut extends Thread {
   
   ReqQueue		myQueue;
   Logging		myLog;
   Fetch		f;
   Request		currentRequest;
   FetchResult	result;
   public 		boolean   idle  = true;

   // Use default constructor

   public void init(ReqQueue yourQueue, Logging  yourLog) {
      setDaemon(true);
	myQueue = yourQueue;
	myLog   = yourLog;
	f	  = new Fetch();
   }

   public void run() {

	// Loop until killed by the world
	while(true) {
		if (myQueue.size() > 0)
		{
			idle   	 = false;
			currentRequest = myQueue.get();

			switch(currentRequest.type) {
			
			   case Request.reqPUT: 
		            try {
			         URL url 	= new URL(currentRequest.text);
				   result   = f.get(url);
			
  			   	   if (result == null) {
				      System.out.println("NULL result!");	
			   	   } else {		
		   	             myLog.post("P : " + result.status + 
				       "  t=" + result.time + " s=" + result.size + "\n      : " + currentRequest.text);
			   	   }

			      } catch (MalformedURLException em) {

			         myLog.post("DISCARD: Script item discarded do to malformed URL");
			         myLog.post("       : " + currentRequest.text);
			      }
				break;

			   case Request.reqWAIT:
				try {
				   this.sleep(currentRequest.intParam);
				   // myLog.post("WAIT: CHUTE Cleared after "+currentRequest.intParam);
				} catch (Exception e) {
				   myLog.post("ERROR: Tasking error on chute WAIT."); 		
				}
				break;

			   default:
				   myLog.post("ERROR: Unknown request in chute."); 		
				   break;	
			}

		} else {
			idle = true;
			try {
				this.sleep(200);
			} catch (InterruptedException e) {
				// Like I give a rats-ass about this lame exception...
			}
		}
		
	}	

   }

}     

